<template>
    <div class="page">
        <a-spin :spinning="spinning" style="height:100vh;max-height:none">
            <div class="title flexBetweenCenter">
                <div style="color:#fff" class="ml-20">
                    {{ fileName }}
                </div>
                <a-button ghost @click="onSubmit" style="margin-right:60px;color: #fff;">提交签署</a-button>
            </div>
            <div class="content flexBetween">

                <div class="checkSign flexStart">
                    <div style="width:44px;height:100%;background:#F5F7F9;">
                        <div class="pen" @click="onDetail">
                            <img src="./pen.png" alt="" />
                        </div>

                    </div>
                    <transition-group name="left">
                        <div v-if="checkDetailFlag" class="checkDetail">
                            <div class="flexBetweenCenter mb-20">
                                <div style="width:50px">
                                    签名
                                </div>
                                <div style="cursor: pointer;">
                                    <img src="./cha.png" alt="" @click="onClose">
                                </div>

                            </div>
                            <div class="mb-10">
                                <a-button type="primary" size="small">验证签名</a-button>
                            </div>
                            <div class="line">

                            </div>
                            <a-collapse v-model:activeKey="activeKey" :bordered="false">
                                <template #expandIcon="{ isActive }">
                                    <myIcon type="caret-right-outlined" :rotate="isActive ? 45 : 0" />
                                </template>
                                <a-collapse-panel :header="item.name" v-for="(item, index) in signCheckList"
                                    :key="index" class="signCheckList">
                                    <div class="flexStartCenter" style="color:#00C3A0" v-if="item.type == 0">
                                        <div>
                                            <img src="./youxiao.png" alt=""
                                                style="vertical-align: -1px;margin-right: 2px;">
                                        </div>
                                        <div>
                                            签名有效
                                        </div>
                                    </div>
                                    <div class="flexStartCenter" style="color:#F22424" v-if="item.type == 1">
                                        <div>
                                            <img src="./weitongguo.png" alt=""
                                                style="vertical-align: -1px;margin-right: 2px;">
                                        </div>
                                        <div>
                                            签名未通过
                                        </div>
                                    </div>
                                    <div class="flexStartCenter" style="color:#F6AE21" v-if="item.type == 2">
                                        <div>
                                            <img src="./weizhi.png" alt=""
                                                style="vertical-align: -1px;margin-right: 2px;">
                                        </div>
                                        <div>
                                            签名有效性未知
                                        </div>
                                    </div>
                                    <p>{{ item.person ? `由“${item.person}”签名` : '' }}</p>
                                    <p>自签名以来，文档{{ item.edit ? '有' : '未' }}被修改</p>
                                    <p>签名者身份{{ item.identity ? '有' : '无' }}效</p>
                                    <p>文档位置：第{{ item.page }}页</p>
                                </a-collapse-panel>

                            </a-collapse>


                        </div>
                    </transition-group>
                </div>
                <div class="pdfDiv" id="pdfDiv" ref="pdfDiv" @scroll.passive="getScroll">
                    <div v-for="item in imgList" :key="item.ref" :ref="item.ref" style="margin-bottom: 20px"
                        class="imgDiv">
                        <img :src="item.url" alt="" style="width: 100%;" draggable="false">
                        <div class="signListItemPre" v-for="(item2, index) in item.pdfSignList" :key="item2.id" :style="{
                            top: `${item2.top}px`,
                            left: `${item2.left}px`,
                            'z-index': `${item2.zIndex}`,
                        
                        }">

                            <FreeDrag class="signDiv">
                                <img :ref="item2.vid" :class="item2.id" :src="item2.imgUrl"
                                    style="width: 100%;height: 100%;cursor: move;"
                                    @mousedown="(e) => mousedown(e, item2)" @dragstart.prevent @dragover.prevent />
                            </FreeDrag>


                            <!-- 删除 -->
                            <div class="closeIcon" @click="delSign(item.pdfSignList, index)">
                                <myIcon type="close-outlined" style="color:#fff" />
                            </div>
                            <!-- 设置日期 -->
                            <!-- <div style="position:absolute;left:0px;top:-27px;"> -->
                            <!-- @click="setDate(item2)" -->
                            <!-- <myIcon type="drag-outlined" style="color:#1890ff;font-size:25px" /> -->
                            <!-- <a-button type="primary" size="small" style="background:#4F8BFF">拖拽</a-button> -->
                            <!-- </div> -->
                        </div>
                    </div>
                </div>
                <div class="mySign">
                    <div style="height:40px;line-height:40px;margin-bottom:10px">
                        我的{{ signType ? '签名' : '印章' }}

                    </div>
                    <div class="line mb-15" style="width:150px">

                    </div>
                    <div class="mySignList">
                        <div class="flexCenter addSign" @click="handSign">
                            <span style="font-size: 20px;">+</span>
                            <span>添加签名</span>
                        </div>
                        <div v-for="item in signList" :key="item.id" :vid="item.id" class="signListItem"
                            draggable="true" @dragstart="(e) => dragstart(e, item)" @dragend="dragend">
                            <img :src="item.imgUrl" alt="" style="width:100%;height:100%;object-fit: contain;">
                        </div>
                    </div>
                </div>

                <div class="foot flexStartCenter" style="padding-left:15px;height: 50px;background:#F5F7F9">
                    <div class="mr-15">共 {{ pageTotal }} 页</div>
                    <a-pagination :current="page" size="small" :total="pageNum(pageTotal)" :page-size="pageSize"
                        @change="pageChange" show-quick-jumper>
                    </a-pagination>
                </div>
            </div>

        </a-spin>
        <a-modal title="添加签名" v-model:visible="qrCodevisible" :footer="null">
            <div style="text-align:center">
                <div class="mb-30">
                    请使用微信扫一扫，扫描下方二维码
                </div>
                <qrcode-vue :value="qrcodeValue" level="H" :size="200" />
            </div>

        </a-modal>
        <a-modal v-model:visible="dateVisible" :footer="null">
            <p>设置日期</p>
        </a-modal>
        <a-modal v-model:visible="signVisible" title="提示" :centered="true">
            <p style="text-align:center;padding:20px 0">暂无印章，请联系管理员申请印章</p>
            <template #footer>
                <div style="text-align:center">
                    <a-button type="primary" @click="signVisible = false">我知道了</a-button>
                </div>

            </template>
        </a-modal>
    </div>

</template>

<script>

import FreeDrag from '../draggable/8drag.vue'
import QrcodeVue from 'qrcode.vue'
import html2canvas from "html2canvas"
export default {
    components: { FreeDrag, QrcodeVue, html2canvas },
    data() {
        return {
            activeKey: [0, 1, 2, 3, 4],
            signType: 1,
            fileName: '',
            signCheckList: [
                {
                    name: '签名1',
                    type: 0,
                    person: '江苏纳言股份有限公司',
                    edit: false,
                    identity: true,
                    page: '1'
                },
                {
                    name: '签名2',
                    type: 1,
                    person: '江苏纳言股份有限公司',
                    edit: false,
                    identity: true,
                    page: '2'
                },
                {
                    name: '签名3',
                    type: 2,
                    person: '江苏纳言股份有限公司',
                    edit: false,
                    identity: true,
                    page: '3'
                }
            ],
            qrCodevisible: false,

            signList: [
                { id: 'img1', imgUrl: 'https://img0.baidu.com/it/u=922640307,3241298194&fm=253&fmt=auto&app=138&f=JPEG?w=736&h=500' }, { id: 'img2', imgUrl: 'https://img1.baidu.com/it/u=1167462586,3936780745&fm=253&fmt=auto&app=138&f=JPEG?w=450&h=298' }
            ],
            qrcodeValue: 'http://www.baidu.com/',
            imgList: [
                {
                    url: 'https://sh-wellsign-xcx.oss-cn-shanghai.aliyuncs.com/oXRh1qdgQikaeFRc/rPSU5LVOpp/file/x2uXhXHaqDq/wvqdH0003.jpg?WH=0.71',
                    ref: 'targetContent',
                    pdfSignList: []
                },
                {
                    url: 'https://sh-wellsign-xcx.oss-cn-shanghai.aliyuncs.com/oXRh1qdgQikaeFRc/rPSU5LVOpp/file/x2uXhXHaqDq/wvqdH0003.jpg?WH=0.71',
                    ref: 'targetContent2',
                    pdfSignList: []
                },
                {
                    url: 'https://sh-wellsign-xcx.oss-cn-shanghai.aliyuncs.com/oXRh1qdgQikaeFRc/rPSU5LVOpp/file/x2uXhXHaqDq/wvqdH0003.jpg?WH=0.71',
                    ref: 'targetContent3',
                    pdfSignList: []
                },
            ],
            pdfSignList: [],
            dragItem: null,
            moveItem: null,
            movingNodeOffset: {},
            spinning: false,
            page: 1,
            pageSize: 1,
            pageTotal: 3,
            dateVisible: false,
            //VueDragResize
            vw: 150,
            vh: 70,
            top: 0,
            left: 0,

            //验签
            checkDetailFlag: false,

            signVisible: false
        }
    },
    created() {
        this.vw = 150 + 'px'
        this.vh = 70 + 'px'
    },
    mounted() {
        this.fileName = '文件名称'
        window.addEventListener('scroll', this.getScroll, true)

    },
    // 页面销毁前
    beforeDestroy: function () {
        window.removeEventListener("scroll", this.getScroll);
    },
    methods: {
        //关闭验签
        onClose() {
            this.checkDetailFlag = false
        },
        //打开验签
        onDetail() {
            this.checkDetailFlag = true
        },

        //设置日期
        setDate(obj) {
            this.dateVisible = true
        },
        //删除签字
        delSign(arr, index) {
            arr.splice(index, 1)
        },
        getScroll(event) {
            // 获取滚动条离顶部的距离
            // let top = event.target.scrollTop;

            if (this.imgList.length>0) {
                var pdfDiv = document.getElementById("pdfDiv")
                var imgHeight = document.getElementsByClassName("imgDiv");
                var page = Math.ceil(
                    (pdfDiv.scrollTop + pdfDiv.clientHeight) /
                    imgHeight[0].offsetHeight
                );
                this.page=page<1?1:page
                this.page=page>this.pageTotal?this.pageTotal:page
                

            }


            // console.log(top)
            // var oDiv = document.getElementById("pdfDiv");
            // let pdfDivHeight = (window.getComputedStyle(oDiv).height.replace('px', '')) - 0
            // let page = top / pdfDivHeight
            // page = Math.round(page)
            // this.page = page + 1
        },

        //手动签字
        handSign() {
            this.qrCodevisible = true
            console.log(this.qrCodevisible);
        },
        //提交
        onSubmit() {
            this.spinning = true

            this.imgList.forEach(element => {
                // console.log(element);
                element.pdfSignList.forEach(item => {

                    let imgSign = document.getElementsByClassName(item.id)

                    const config = {
                        useCORS: true,
                        scrollX: 0,
                        scrollY: 0,
                    }
                    html2canvas(imgSign[0], config).then(res => {
                        let imgUrl = res.toDataURL('image/png')
                        item.base64 = imgUrl
                        item.left = item.left + 5
                        item.top = item.top + 5
                    })
                })
            });

            console.log(this.imgList);


            setTimeout(() => {
                this.spinning = false
            }, 2000);
        },

        pageNum(val) {
            if (val == 0) {
                return 1
            } else {
                return val
            }
        },
        pageChange(current, pageSize) {
            this.page = current
            this.pageSize = pageSize
            // let refDiv=
            document.getElementsByClassName('imgDiv')[current - 1].scrollIntoView({ behavior: 'smooth', block: 'start' })

            //         var contract = document.getElementsByClassName("contract-my-back")[0];
            //   var imgHeight = document.getElementsByClassName("width800")[0];
            //   contract.scrollTop =
            //     imgHeight.clientHeight * self.nowPage - contract.clientHeight;
        },
        //拖拽
        dragstart(e, item) {
            this.dragItem = item;
            this.dragItem.vid = e.currentTarget.getAttribute("vid")
            let imgDivDoms = document.querySelectorAll('.imgDiv')
            // 设置元素的放置行为——移动
            imgDivDoms[this.page - 1].addEventListener("dragenter", this.dragenter);
            // 在目标元素经过 必须要阻止默认行为 否则不能触发drop
            imgDivDoms[this.page - 1].addEventListener("dragover", this.dragover);
            // 离开目标元素时设置元素的放置行为——不能拖放
            imgDivDoms[this.page - 1].addEventListener("dragleave", this.dragleave);
            // 拖动元素在目标元素松手时添加元素到画布
            imgDivDoms[this.page - 1].addEventListener("drop", this.drop);
        },
        dragend(e) {
            let imgDivDoms = document.querySelectorAll('.imgDiv')
            imgDivDoms[this.page - 1].removeEventListener("dragenter", this.dragenter);
            imgDivDoms[this.page - 1].removeEventListener("dragover", this.dragover);
            imgDivDoms[this.page - 1].removeEventListener("dragleave", this.dragleave);
            imgDivDoms[this.page - 1].removeEventListener("drop", this.drop);

        },
        dragenter(e) {
            e.dataTransfer.dropEffect = "move";
        },
        dragover(e) {
            e.preventDefault();
        },
        dragleave(e) {
            e.dataTransfer.dropEffect = "none";
        },
        drop(e) {
            console.log(e);
            const { vid, imgUrl } = this.dragItem;
            let obj = this.imgList[this.page - 1]
            obj.pdfSignList.push({
                top: e.offsetY - 65,
                left: e.offsetX - 140,
                zIndex: 3,
                id: 'img' + new Date().getTime().toString(),
                vid,
                imgUrl
            });
            this.dragItem = null;

        },
        mousedown(e, item) {


            this.moveItem = item;

            // 鼠标点击图片的位置
            this.movingNodeOffset = {
                offsetX: e.offsetX,
                offsetY: e.offsetY,
            };
            // console.log(e.offsetX);
            document.addEventListener("mousemove", this.mousemove);
            document.addEventListener("mouseup", this.mouseup);
        },
        mousemove(e) {
            const _this = this;
            // console.log(e);
            let imgDivDoms = document.querySelectorAll('.imgDiv')
            let { clientX, clientY, offsetX, offsetY } = e;
            let obj = this.imgList[this.page - 1]
            const moveIdx = obj.pdfSignList.findIndex(function (o) {
                return o.id === _this.moveItem.id;
            });
            let newList = JSON.parse(JSON.stringify(obj.pdfSignList));
            var oDiv = imgDivDoms[this.page - 1]
            let Rect = oDiv.getBoundingClientRect()
            //签字的坐标
            console.log(clientY);
            console.log(Rect.y);
            console.log(_this.movingNodeOffset.offsetY);
            newList[moveIdx].top = clientY - Rect.y - _this.movingNodeOffset.offsetY;
            newList[moveIdx].left = clientX - Rect.x - _this.movingNodeOffset.offsetX;
            //文件图片的宽高
            let pdfDivHeight = (window.getComputedStyle(oDiv).height.replace('px', '')) - 0
            let pdfDivWidth = (window.getComputedStyle(oDiv).width.replace('px', '')) - 0
            // console.log(_this.moveItem.id);
            let imgDom = document.getElementsByClassName(_this.moveItem.id)[0]
            let imgHeight = (window.getComputedStyle(imgDom).height.replace('px', '')) - 0
            let imgWidth = (window.getComputedStyle(imgDom).width.replace('px', '')) - 0

            // 坐标最大范围
            let x = pdfDivWidth - imgWidth
            let y = pdfDivHeight - imgHeight
            newList[moveIdx].top = newList[moveIdx].top < 0 ? 0 : newList[moveIdx].top
            newList[moveIdx].top = newList[moveIdx].top > y ? y : newList[moveIdx].top

            newList[moveIdx].left = newList[moveIdx].left < 0 ? 0 : newList[moveIdx].left
            newList[moveIdx].left = newList[moveIdx].left > x ? x : newList[moveIdx].left
            obj.pdfSignList = newList;
        },
        mouseup(e) {
            document.removeEventListener("mousemove", this.mousemove);
            document.removeEventListener("mouseup", this.mouseup);
        },

    }
}
</script>
<style scoped>
.title {
    background: #0170FE;
    height: 46px;
}

.content {
    width: 100%;
    min-width: 1240px;
    background: #EBECEC;
    height: calc(100vh - 46px);
}

.pdfDiv {
    width: 800px;
    text-align: center;
    padding-top: 4px;
    height: calc(100vh - 95px);
    overflow: auto;
    background: #EBECEC;
    margin-right: 20px;
}

.imgDiv {
    position: relative;
    overflow: hidden;
}

.mySign,
.checkSign {
    background: #F5F7F9;
    padding: 23px;
    padding-top: 10px;
    width: 207px;
    height: calc(100vh - 46px);
    overflow: auto;
}

.foot {
    position: absolute;
    width: 100%;
    bottom: 0;
}

.signListItem {
    width: 150px;
    height: 70px;
    margin-bottom: 20px;
    background: #fff;
    border: 1px solid #DCDFE6;
    object-fit: cover;
}

.addSign {
    width: 150px;
    height: 70px;
    margin-bottom: 20px;
    flex-direction: column;
    color: #9DA3AC;
    font-size: 14px;
    background: url('./addKuang.png') no-repeat
}

.signListItemPre {
    user-select: none;
    background: none;
    /* width: 150px;
    height: 70px; */
    /* border: 1px dashed #1890ff; */
    position: absolute;
    /* padding: 3px; */
}

.closeIcon {
    position: absolute;
    right: -8px;
    top: -12px;
    cursor: pointer;
    background: #4F8BFF;
    width: 18px;
    height: 18px;
    line-height: 18px;
    border-radius: 18px;
}

::v-deep .content-container {
    overflow: hidden;
}

::v-deep .vdr {
    position: static;
}


.checkSign {
    padding: 0;
    width: 282px;
    margin-right: 20px;
    background: #EBECEC;
}

.checkDetail {
    background: #F5F7F9;
    border-left: 1px solid #E4E6EA;
    border-right: 1px solid #E4E6EA;
    width: 238px;
    height: 100%;
    padding: 18px 14px;
}

.pen {
    width: 34px;
    height: 34px;
    background: #DFE4E9;
    margin: 0 auto;
    margin-top: 10px;
    text-align: center;
    border-radius: 5px;
    line-height: 30px;
    cursor: pointer;
}

.left-enter,
.left-leave-to {
    transform: translateX(-100%);
}

.left-leave,
.left-enter-to {
    transform: translateX(0);

}


.left-enter-active,
.left-leave-active {
    transition: all 0.2s
}

.closeIcon {
    position: absolute;
    left: 0px;
    top: -20px;
    cursor: pointer;
    background: #4F8BFF;
    width: 18px;
    height: 18px;
    line-height: 18px;
    border-radius: 18px;
}

::v-deep .ant-collapse-borderless>.ant-collapse-item {
    border: none
}

.signCheckList p {
    margin: 0;
    font-size: 13px;

}

::v-deep .ant-collapse>.ant-collapse-item>.ant-collapse-header {
    padding-left: 0;
    padding-bottom: 5px;
}

::v-deep .ant-collapse>.ant-collapse-item>.ant-collapse-header .ant-collapse-arrow {
    margin-right: 5px;
    vertical-align: -3px;
}

::v-deep .ant-collapse-content>.ant-collapse-content-box {
    padding-right: 0;
}
</style>
